import requests
from fake_useragent import UserAgent
import pymongo
from pyquery import PyQuery as pq
import json
import random
import time


clien=pymongo.MongoClient(host='数据库地址')
db=clien.Singer_ID
coll=db.Name

ua=UserAgent()

def get_html(URL):
    headers = {
        'User-Agent':
            ua.random}
    try:
        html = requests.get(URL, headers=headers).text
        return html
    except BaseException:
        print('request error')
        pass


def get_top50(html):
    doc=pq(html)

    #歌曲的ID
    Song_id=[]

    #歌曲的名字
    Song_Name=[]

    The_all=doc('.f-hide #song-list-pre-cache a').items()

    for i in The_all:

        The_ID=str(i.attr('href'))
        ID=The_ID.split('=')
        Song_id.append(ID[1])

        #获取歌曲名字

        The_Name=i.text()
        Song_Name.append(The_Name)

        #print(i)
    return zip(Song_id,Song_Name)


def the_lyrics(Song_id):

    url = 'http://music.163.com/api/song/lyric?id={}&lv=-1&kv=-1&tv=-1'.format(Song_id)
    headers={
        'User-Agent':ua.random
    }
    html=requests.get(url,headers=headers).text
    json_obj=json.loads(html)
    initial_lyric = json_obj['lrc']['lyric']
    #The_lyrics=html.get('lrc').get('lyric')
    return initial_lyric

def Download_the_lyrics(Song_Name,lyrics):
    print('正在保存{}  请稍后。。。。'.format(Song_Name))
    with open('F:/新建文件夹/{}.txt'.format(Song_Name),'a',encoding='utf8')as f:
        f.write(lyrics)



test=input('请输入歌手的名字:')
for i in coll.find({'歌手名字': {'$regex': test,'$options':'$i'}}):
    top50url = 'https://music.163.com/artist?id={}'.format(i['歌手的ID'])

    for u in get_top50(get_html(top50url)):

        lyric = the_lyrics(u[0])

        Download_the_lyrics(u[1],lyric)

        time.sleep(random.randint(0,6))






